﻿/*
 * DotNetCrypt - an open source library of cryptographic algorithms for .NET
 * Copyright (C) 2009 David Musgrove
 * 
 * This file is part of DotNetCrypt.
 *
 * DotNetCrypt is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DotNetCrypt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace DotNetCrypt
{
    /// <summary>
    /// Computes the <see cref="MD4" /> hash for the input data using this
    /// managed library. 
    /// </summary>
// ReSharper disable InconsistentNaming
    public sealed class MD4Managed : MD4
// ReSharper restore InconsistentNaming
    {
        private uint[] _internalState;
        static private readonly int[] _shifts = { 3, 7, 11, 19, 3, 7, 11, 19, 3, 7, 11, 19, 3, 7, 11, 19, 3, 5, 9, 13, 3, 5, 9, 13, 3, 5, 9, 13, 3, 5, 9, 13, 3, 9, 11, 15, 3, 9, 11, 15, 3, 9, 11, 15, 3, 9, 11, 15 };
        static private readonly int[] _round1Indices = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 };
        static private readonly int[] _round2Indices = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
        static private readonly uint[] _table = { 0x0, 0x5a827999, 0x6ed9eba1 };

        /// <summary>
        /// Initializes a new instance of the <see cref="MD4Managed" />
        /// class using the managed library.
        /// </summary>
        public MD4Managed()
        {
            InitialiseState();
        }

        private void InitialiseState()
        {
            _internalState = new uint[4];
            _internalState[0] = 0x67452301;
            _internalState[1] = 0xEFCDAB89;
            _internalState[2] = 0x98BADCFE;
            _internalState[3] = 0x10325476;
            Count = 0;
        }

        /// <summary>
        /// Initializes an implementation of the
        /// <see cref="T:System.Security.Cryptography.HashAlgorithm"/> class.
        /// </summary>
        public override void Initialize()
        {
            InitialiseState();
        }

        /// <summary>
        /// Transforms a single block of bytes using <see cref="MD4" />.
        /// </summary>
        /// <param name="array">
        /// An array containing the block of bytes.
        /// </param>
        /// <param name="ibStart">
        /// The offset of the start of the block within the array.
        /// </param>
        protected override void TransformBlock(byte[] array, int ibStart)
        {
            var working = new uint[16];

            uint a = _internalState[0];
            uint b = _internalState[1];
            uint c = _internalState[2];
            uint d = _internalState[3];

            for (int i = 0; i < 16; i++)
            {
                working[i] = array[ibStart++] |
                    ((uint)array[ibStart++] << 8) |
                    ((uint)array[ibStart++] << 16) |
                    ((uint)array[ibStart++] << 24);
                a += (d ^ (b & (c ^ d))) + working[i];
                a = ((a << _shifts[i]) | (a >> (32 - _shifts[i])));
                uint temp = d;
                d = c;
                c = b;
                b = a;
                a = temp;
            }
            for (int i = 0; i < 16; i++)
            {
                a += (((b ^ c) & d) ^ (b & c)) + working[_round1Indices[i]] + _table[1];
                int shift = i + 16;
                a = ((a << _shifts[shift]) | (a >> (32 - _shifts[shift])));
                uint temp = d;
                d = c;
                c = b;
                b = a;
                a = temp;
            }
            for (int i = 0; i < 16; i++)
            {
                a += (b ^ c ^ d) + working[_round2Indices[i]] + _table[2];
                int shift = i + 32;
                a = ((a << _shifts[shift]) | (a >> (32 - _shifts[shift])));
                uint temp = d;
                d = c;
                c = b;
                b = a;
                a = temp;
            }

            _internalState[0] += a;
            _internalState[1] += b;
            _internalState[2] += c;
            _internalState[3] += d;
        }

        /// <summary>
        /// Finalizes the hash computation after the last data is processed
        /// by the cryptographic stream object.
        /// </summary>
        /// <returns>
        /// The computed hash code.
        /// </returns>
        protected override byte[] HashFinal()
        {
            var block = new byte[0x10];
            int bytesRemaining = 0x40 - ((int)(Count & 0x3fL));
            int blockSize = 0x40;
            if (bytesRemaining <= 8)
            {
                blockSize += 0x40;
            }
            var partIn = new byte[blockSize];
            FinalBlock.CopyTo(partIn, 0);
            partIn[FinalBlock.Length] = 0x80;
            long num2 = Count * 8L;
            partIn[blockSize - 1] = (byte)((num2 >> 0x38) & 0xffL);
            partIn[blockSize - 2] = (byte)((num2 >> 0x30) & 0xffL);
            partIn[blockSize - 3] = (byte)((num2 >> 40) & 0xffL);
            partIn[blockSize - 4] = (byte)((num2 >> 0x20) & 0xffL);
            partIn[blockSize - 5] = (byte)((num2 >> 0x18) & 0xffL);
            partIn[blockSize - 6] = (byte)((num2 >> 0x10) & 0xffL);
            partIn[blockSize - 7] = (byte)((num2 >> 8) & 0xffL);
            partIn[blockSize - 8] = (byte)(num2 & 0xffL);
            Count = blockSize;
            HashCore(partIn, 0, blockSize);
            Utils.WriteWordsIntoBytesBigEndian(_internalState, block);
            HashValue = block;
            return block;
        }
    }
}
